<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of HouseModel
 *
 * @author wangnaixin
 */
namespace Admin\Model;
use Think\Model;
class AttachmentModel  extends Model {
    //put your code here
    protected  $tableName = 'attachment';
    
    //新增附件
    public function saveAttachement($data,$extension,$userId=''){
    	$data['isimage'] = 0;
    	$data['dateline'] = time();
    	$data['user_id'] = $userId ? $userId : session('userId');
    	if (in_array(strtolower($extension), array('jpg','jpeg','gif','png'))) {
    		$data['isimage'] = 1;
    	}
    	$rs = $this->data($data)->add();

    	return $this->getLastInsID();
    }
    
    //根据id更新附件
    public function updateAttachement($data,$ids){
    	if (!$ids) {
    		return;
    	}
    	$rs = $this->where(array('id'=>array('in',$ids)))->save($data);
    	return $rs;
    }
    
    //删除指定id的附件记录
    public function deleteAttachement($ids) {
    	if (!$ids) {
    		return;
    	}
    	$rs = $this->where(array('id'=>array('in',$ids)))->delete();
    	return $rs;
    }
    
    //根据附件类型和外部对象id删除附件
    public function deleteAttachementByType($rel_id,$type) {
    	$rs = $this->where(array('rel_id'=>$rel_id,'type'=>$type))->delete();
    	return $rs;
    }
    
    //根据外部对象id和类型，获取附件信息
    public function getAttaches($rel_id,$type){
    	$list = $this->where(array('rel_id'=>$rel_id,'type'=>$type))->select();
    	return $list;
    }
    
    //根据附件id获取附件明细
    public function getAttacheById($id){
    	$attache = $this->where(array('id'=>$id))->find();
    	return $attache;
    }
    
    public function getAvaliableCount($id,$type,$rel_id){
    	if (!$id) {
    		return 1;
    	}
    	$where = array(
    		'id' => array('not in',$id),
    		'type' => $type,
    		'rel_id' => $rel_id
    	);
    	$count = $this->where($where)->count();
    	return $count;
    }
    
    /**
     * 根据附件id和缩略图类型，返回处理后的附件
     * @param array $data 附件数据
     * @param string $type 附件类型
     * @param string $prefix 缩略图类型，可选值 big middle small
     * @return array
     */
    public function getAttacheByType($data=array(),$type='',$prefix=''){
    	return $data;
    	$attaches = $data;
    	$image_crop = C('IMAGE_CROP');
    	$thumb = $image_crop[$type];
    	if (!$data || !$prefix || !$thumb['prefix'] || !in_array($prefix.'_', explode(',', $thumb['prefix']))) {
    		return $attaches;
    	}
    	foreach ($attaches as $key => $attache) {
    		$attache_full = $attache['attachment'];
    		$attache_name = pathinfo($attache_full,PATHINFO_BASENAME);
    		$prefixFile = str_replace($attache_name, $prefix.'_'.$attache_name, $attache_full);
    		if (!file_exists(ROOT_PATH_ABSOLUTE.$prefixFile)) {
    			continue;
    		}
    		$attaches[$key]['attachment'] = $prefixFile;
    	}
    	return $attaches;
    }
}
